package com.yuwubao.hz_International.controllers.sys;

import com.yuwubao.hz_International.entities.AcountDetailEntity;
import com.yuwubao.hz_International.entities.ConsumerEntity;
import com.yuwubao.hz_International.entities.StoreEntity;
import com.yuwubao.hz_International.entities.vo.ConsumerShiftStoreVo;
import com.yuwubao.hz_International.entities.vo.ConsumerVo;
import com.yuwubao.hz_International.services.AcountDetailService;
import com.yuwubao.hz_International.services.AppService;
import com.yuwubao.hz_International.services.ConsumerService;
import com.yuwubao.hz_International.services.StoreService;
import com.yuwubao.hz_International.util.Const;
import com.yuwubao.hz_International.util.PageUtil;
import com.yuwubao.hz_International.util.RestApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyu on 2018/1/29.
 */
@RestController
@RequestMapping("/sys/consumerManage")
@Transactional
@CrossOrigin
@Api(value = "后台接口")
public class ConsumerManageController {

    private final static Logger logger = LoggerFactory.getLogger(ConsumerManageController.class);

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private AcountDetailService acountDetailService;

    @Resource
    private AppService appService;

    /**
     * 获取会员列表
     * @param consumerName 查询会员名
     * @param index  第几页
     * @param size  每页几条
     * @return
     */
    @GetMapping("/findConsumerList")
    @ApiOperation(value = "获取会员列表接口")
    public RestApiResponse<PageUtil<ConsumerVo>> findConsumerList(@ApiParam(required = false,value = "会员名")@RequestParam(defaultValue = "", required = false) String consumerName,
                                                                  @ApiParam(required = false,value = "第几页")@RequestParam(defaultValue = "1", required = false) int index,
                                                                  @ApiParam(required = false,value = "每页几条")@RequestParam(defaultValue = "10", required = false) int size) {
        RestApiResponse<PageUtil<ConsumerVo>> result = new RestApiResponse<PageUtil<ConsumerVo>>();
        try {
            PageUtil<ConsumerVo> pageUtil = new PageUtil<ConsumerVo>();
            List<ConsumerVo> list = consumerService.findConsumerList(consumerName, index-1, size);
            List<ConsumerVo> consumerList = consumerService.findConsumerList(consumerName, 0, 0);
            pageUtil.setTotalElements(consumerList.size());
            pageUtil.setTotalPages(size, consumerList.size());
            pageUtil.setIndex(index);
            pageUtil.setSize(size);
            pageUtil.setList(list);
            result.successResponse(Const.SUCCESS, pageUtil);
        } catch (Exception e) {
            logger.warn("获取会员列表异常", e);
            result.failedApiResponse(Const.FAILED, "获取会员列表异常");
        }

        return result;
    }

    /**
     * 查看会员详情
     * @param consumerId  会员id
     * @return
     */
    @GetMapping("/getConsumerDetail")
    @ApiOperation(value = "查看会员详情接口")
    public RestApiResponse<ConsumerVo> getConsumerDetail(@ApiParam(required = true,value = "会员id")@RequestParam int consumerId) {
        RestApiResponse<ConsumerVo> result = new RestApiResponse<ConsumerVo>();
        try {
            ConsumerVo consumerVo = consumerService.findById(consumerId);
            if (consumerVo != null) {
                result.successResponse(Const.SUCCESS, consumerVo);
                return result;
            }
            result.failedApiResponse(Const.FAILED, "此会员不存在");
        } catch (Exception e) {
            logger.warn("获取会员信息异常", e);
            result.failedApiResponse(Const.FAILED, "获取会员信息异常");
        }
        return result;
    }

    /**
     * 会员编辑
     * @param consumerVo
     * @return
     */
    /*@PostMapping("/updateConsumer")
    public RestApiResponse<ConsumerVo> updateConsumer(@RequestBody ConsumerVo consumerVo) {
        RestApiResponse<ConsumerVo> result = new RestApiResponse<ConsumerVo>();
        try {
            ConsumerEntity consumerEntity = consumerService.findOne(consumerVo.getId());
            if (consumerEntity == null) {
                result.failedApiResponse(Const.FAILED, "修改失败,此会员不存在");
                return result;
            }
            if (consumerVo.getGiftMoney()!= consumerEntity.getGiftMoney()
                    || consumerEntity.getMoney() != consumerVo.getMoney()
                    || consumerEntity.getBonous() != consumerVo.getBonous()
                    || consumerEntity.getWelfareMoney() != consumerVo.getWelfareMoney()) {
                result.failedApiResponse(Const.FAILED, "不能修改账户额度");
                return result;
            }
            consumerEntity.setName(consumerVo.getName());
            ConsumerEntity newConsumerEntity = consumerService.update(consumerEntity);
            if (newConsumerEntity != null) {
                result.successResponse(Const.SUCCESS, consumerVo, "修改成功");
                return result;
            }
            result.failedApiResponse(Const.FAILED, "修改失败");
        } catch (Exception e) {
            logger.warn("修改会员异常", e);
            result.failedApiResponse(Const.FAILED, "修改会员异常");
        }
        return result;
    }*/

    /**
     * 删除会员
     * @param consumerId  会员id
     * @return
     */
    @PostMapping("/deleteConsumer")
    @ApiOperation(value = "删除会员接口")
    public RestApiResponse<Boolean> deleteConsumer(@RequestBody int[] consumerId) {
        RestApiResponse<Boolean> result = new RestApiResponse<Boolean>();
        try {
            for (int i: consumerId) {
                ConsumerVo consumerVo = consumerService.findById(i);
                if (consumerVo == null) {
                    result.failedApiResponse(Const.FAILED, "删除失败,此会员不存在");
                    return result;
                }
                if (consumerVo.getMoney().signum() > 0
                        || consumerVo.getBonous().signum() > 0
                        || consumerVo.getGiftMoney().signum() > 0
                        || consumerVo.getWelfareMoney().signum() > 0) {
                    result.failedApiResponse(Const.FAILED, "删除失败,此用户账户还有余额");
                    return result;
                }
                ConsumerEntity consumerEntity = consumerService.delete(i);
                if (consumerEntity == null) {
                    result.failedApiResponse(Const.FAILED, "删除失败");
                    return result;
                }
            }
            result.successResponse(Const.SUCCESS, true, "删除成功");
        } catch (Exception e) {
            logger.warn("删除会员异常", e);
            result.failedApiResponse(Const.FAILED, "删除会员异常");
        }
        return result;
    }

    /**
     * 会员转商家
     * @param consumerShiftStoreVo
     * @return
     */
    @PostMapping("/consumerShiftStore")
    @ApiOperation(value = "会员转商家接口")
    public RestApiResponse<StoreEntity> consumerShiftStore(@RequestBody ConsumerShiftStoreVo consumerShiftStoreVo) {
        RestApiResponse<StoreEntity> result = new RestApiResponse<StoreEntity>();
        try {
            ConsumerEntity consumerEntity = consumerService.findOne(consumerShiftStoreVo.getConsumerId());
            if (consumerEntity == null) {
                result.failedApiResponse(Const.FAILED, "会员不存在");
                return result;
            }
            StoreEntity storeEntity = storeService.findByConsumerId(consumerEntity.getId());
            if (storeEntity != null) {
                result.failedApiResponse(Const.FAILED, "此会员已经是商家");
                return result;
            }
            consumerEntity.setIsStore(1);
            consumerService.update(consumerEntity);
            ModelMapper model = new ModelMapper();
            StoreEntity entity = model.map(consumerShiftStoreVo, StoreEntity.class);
            entity.setId(0);
            entity.setCreateTime(new Date());
            String[] imageUrl = consumerShiftStoreVo.getImageUrl();
            if (imageUrl.length > 0) {
                for (int i = 0;i< imageUrl.length; i++) {
                    switch (i) {
                        case 0:
                            entity.setImageUrl1(imageUrl[0]);
                            break;
                        case 1:
                            entity.setImageUrl2(imageUrl[1]);
                            break;
                        case 2:
                            entity.setImageUrl3(imageUrl[2]);
                            break;
                    }
                }
            }
            String qrUrl = appService.createQrCode(entity);
            entity.setQrUrl(qrUrl);
            StoreEntity newStoreEntity = storeService.save(entity);
            if (newStoreEntity != null) {
                result.successResponse(Const.SUCCESS, newStoreEntity, "会员转商家成功");
                return result;
            }
            result.failedApiResponse(Const.FAILED, "会员转商家失败");
        } catch (Exception e) {
            logger.warn("会员转商家异常", e);
            result.failedApiResponse(Const.FAILED, "会员转商家异常");
        }
        return result;
    }

    /**
     * 获取会员资金明细
     * @param consumerId  会员id
     * @param beginTime  开始时间
     * @param endTime  结束时间
     * @param index  第几页
     * @param size  每页几条
     * @return
     */
    @GetMapping("/getConsumerFinancialDetails")
    @ApiOperation(value = "获取会员资金明细")
    public RestApiResponse<PageUtil<AcountDetailEntity>> getConsumerFinancialDetails(@ApiParam(required = false, value = "会员id")@RequestParam(required = false, defaultValue = "0") int consumerId,
                                                                                     @ApiParam(required = false, value = "开始时间")@RequestParam(required = false, defaultValue = "")String beginTime,
                                                                                     @ApiParam(required = false, value = "结束时间")@RequestParam(required = false, defaultValue = "")String endTime,
                                                                                     @ApiParam(required = false, value = "第几页")@RequestParam(required = false, defaultValue = "1") int index,
                                                                                     @ApiParam(required = false, value = "每页几条")@RequestParam(required = false, defaultValue = "10") int size) {
        RestApiResponse<PageUtil<AcountDetailEntity>> result = new RestApiResponse<PageUtil<AcountDetailEntity>>();
        try {
            ConsumerEntity consumerEntity = consumerService.findOne(consumerId);
            if (consumerEntity == null) {
                result.failedApiResponse(Const.FAILED, "当前会员不存在");
                return result;
            }
            //添加分页
            PageUtil pageUtil = new PageUtil();
            pageUtil.setIndex(index);
            pageUtil.setSize(size);

            Map<String, String> map = new HashMap<String, String>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            List<AcountDetailEntity> list = acountDetailService.findFinancialDetails(map, pageUtil, consumerId);
            Integer financialDetailsSum = acountDetailService.findFinancialDetailsSum(map, consumerId);
            pageUtil.setTotalElements(financialDetailsSum);
            pageUtil.setTotalPages(size, financialDetailsSum);
            pageUtil.setBuyerName(consumerEntity.getName());
            pageUtil.setList(list);
            result.successResponse(Const.SUCCESS, pageUtil);
        } catch (Exception e) {
            logger.warn("查看会员资金明细异常", e);
            result.failedApiResponse(Const.FAILED, "查看会员资金明细异常");
        }
        return result;
    }
}
